<template>
  <div class="archive-management">
    <div class="header">
      <div class="header-content">
        <router-link class="back-btn" to="/main/renshi/employee/process">
          <i class="el-icon-arrow-left"></i>
          <span>返回</span>
        </router-link>
        <h2 class="page-title">档案管理</h2>
      </div>
    </div>

    <div class="content">
      <!-- 员工选择 -->
      <div class="employee-select">
        <el-select
          v-model="currentEmployee"
          filterable
          remote
          placeholder="请选择员工"
          :remote-method="searchEmployees"
          :loading="employeesLoading"
          @change="handleEmployeeChange"
          style="width: 300px">
          <el-option
            v-for="emp in employees"
            :key="emp.id"
            :label="emp.name"
            :value="emp.id">
            <span>{{ emp.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.department }}</span>
          </el-option>
        </el-select>
      </div>

      <!-- 档案内容 -->
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 证件资料 -->
        <el-tab-pane name="certificates">
          <span slot="label"><i class="el-icon-document"></i> 证件资料</span>
          <div class="certificates-section">
            <div class="section-header">
              <h3>证件列表</h3>
              <el-button type="primary" size="small" @click="uploadCertificate">
                <i class="el-icon-plus"></i> 上传证件
              </el-button>
            </div>
            
            <el-table :data="certificatesList" border style="width: 100%">
              <el-table-column prop="type" label="证件类型" width="150">
                <template slot-scope="scope">
                  <el-tag :type="getCertificateTagType(scope.row.type)">
                    {{ getCertificateTypeName(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="number" label="证件号码" width="180"></el-table-column>
              <el-table-column prop="validDate" label="有效期" width="180">
                <template slot-scope="scope">
                  {{ scope.row.validDate || '长期有效' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === 'valid' ? 'success' : 'danger'">
                    {{ scope.row.status === 'valid' ? '有效' : '已过期' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="previewFile(scope.row)">
                    <i class="el-icon-view"></i> 预览
                  </el-button>
                  <el-button size="mini" type="text" @click="downloadFile(scope.row)">
                    <i class="el-icon-download"></i> 下载
                  </el-button>
                  <el-button size="mini" type="text" class="danger-button" @click="deleteCertificate(scope.row)">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 工作履历 -->
        <el-tab-pane name="workHistory">
          <span slot="label"><i class="el-icon-office-building"></i> 工作履历</span>
          <div class="work-history-section">
            <div class="section-header">
              <h3>工作经历</h3>
              <el-button type="primary" size="small" @click="addWorkExperience">
                <i class="el-icon-plus"></i> 添加经历
              </el-button>
            </div>

            <el-timeline>
              <el-timeline-item
                v-for="(experience, index) in workHistory"
                :key="index"
                :timestamp="getTimeRange(experience.startDate, experience.endDate)"
                :type="getTimelineItemType(experience)">
                <el-card class="experience-card">
                  <div class="experience-header">
                    <h4>{{ experience.company }}</h4>
                    <div class="experience-position">{{ experience.position }}</div>
                  </div>
                  <div class="experience-content">
                    <p>{{ experience.description }}</p>
                  </div>
                  <div class="experience-footer">
                    <el-button type="text" size="small" @click="editWorkExperience(experience)">
                      <i class="el-icon-edit"></i> 编辑
                    </el-button>
                    <el-button type="text" size="small" class="danger-button" @click="deleteWorkExperience(index)">
                      <i class="el-icon-delete"></i> 删除
                    </el-button>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>

        <!-- 培训记录 -->
        <el-tab-pane name="training">
          <span slot="label"><i class="el-icon-reading"></i> 培训记录</span>
          <div class="training-section">
            <div class="section-header">
              <h3>培训记录</h3>
              <el-button type="primary" size="small" @click="addTrainingRecord">
                <i class="el-icon-plus"></i> 添加记录
              </el-button>
            </div>

            <el-table :data="trainingRecords" border style="width: 100%">
              <el-table-column prop="course" label="培训课程" min-width="180"></el-table-column>
              <el-table-column prop="type" label="培训类型" width="120">
                <template slot-scope="scope">
                  <el-tag>{{ scope.row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
              <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
              <el-table-column prop="duration" label="培训时长" width="100">
                <template slot-scope="scope">
                  {{ scope.row.duration }}小时
                </template>
              </el-table-column>
              <el-table-column prop="result" label="培训结果" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getTrainingResultType(scope.row.result)">
                    {{ scope.row.result }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="培训证书" width="120">
                <template slot-scope="scope">
                  <el-button 
                    type="text" 
                    v-if="scope.row.certificate"
                    @click="previewCertificate(scope.row)">
                    查看证书
                  </el-button>
                  <span v-else>无</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="editTrainingRecord(scope.row)">
                    <i class="el-icon-edit"></i> 编辑
                  </el-button>
                  <el-button size="mini" type="text" class="danger-button" @click="deleteTrainingRecord(scope.$index)">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog title="文件预览" :visible.sync="previewVisible" width="80%" class="preview-dialog">
      <div class="preview-container">
        <iframe :src="previewUrl" frameborder="0"></iframe>
      </div>
    </el-dialog>

    <!-- 证件上传对话框 -->
    <el-dialog 
      :title="certificateDialog.type === 'add' ? '上传证件' : '编辑证件'"
      :visible.sync="certificateDialog.visible"
      width="50%">
      <el-form :model="certificateForm" :rules="certificateRules" ref="certificateForm" label-width="100px">
        <el-form-item label="证件类型" prop="type">
          <el-select v-model="certificateForm.type" placeholder="请选择证件类型">
            <el-option label="身份证" value="id"></el-option>
            <el-option label="护照" value="passport"></el-option>
            <el-option label="学历证书" value="education"></el-option>
            <el-option label="职称证书" value="professional"></el-option>
            <el-option label="其他证件" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="number">
          <el-input v-model="certificateForm.number"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="validDate">
          <el-date-picker
            v-model="certificateForm.validDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          <el-checkbox v-model="certificateForm.permanent" style="margin-left: 10px">长期有效</el-checkbox>
        </el-form-item>
        <el-form-item label="证件文件" prop="file">
          <el-upload
            class="certificate-upload"
            action="#"
            :auto-upload="false"
            :file-list="certificateForm.fileList"
            :on-change="handleFileChange"
            :before-upload="beforeUpload">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">支持jpg、png、pdf格式，不超过5MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="certificateForm.remark"
            :rows="3"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="certificateDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitCertificate" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工作经历对话框 -->
    <el-dialog 
      :title="workDialog.type === 'add' ? '添加工作经历' : '编辑工作经历'"
      :visible.sync="workDialog.visible"
      width="50%">
      <el-form :model="workForm" :rules="workRules" ref="workForm" label-width="100px">
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="workForm.company"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="workForm.position"></el-input>
        </el-form-item>
        <el-form-item label="工作时间" prop="dateRange">
          <el-date-picker
            v-model="workForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作描述" prop="description">
          <el-input
            type="textarea"
            v-model="workForm.description"
            :rows="3"
            placeholder="请输入工作内容描述">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="workDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitWorkExperience" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 培训记录对话框 -->
    <el-dialog 
      :title="trainingDialog.type === 'add' ? '添加培训记录' : '编辑培训记录'"
      :visible.sync="trainingDialog.visible"
      width="50%">
      <el-form :model="trainingForm" :rules="trainingRules" ref="trainingForm" label-width="100px">
        <el-form-item label="培训课程" prop="course">
          <el-input v-model="trainingForm.course"></el-input>
        </el-form-item>
        <el-form-item label="培训类型" prop="type">
          <el-select v-model="trainingForm.type" placeholder="请选择培训类型">
            <el-option label="入职培训" value="onboarding"></el-option>
            <el-option label="专业培训" value="professional"></el-option>
            <el-option label="管理培训" value="management"></el-option>
            <el-option label="技能培训" value="skill"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训时间" prop="dateRange">
          <el-date-picker
            v-model="trainingForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="培训时长" prop="duration">
          <el-input-number v-model="trainingForm.duration" :min="0" :max="999"></el-input-number>
          <span class="unit">小时</span>
        </el-form-item>
        <el-form-item label="培训结果" prop="result">
          <el-select v-model="trainingForm.result" placeholder="请选择培训结果">
            <el-option label="优秀" value="excellent"></el-option>
            <el-option label="良好" value="good"></el-option>
            <el-option label="合格" value="pass"></el-option>
            <el-option label="不合格" value="fail"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训证书" prop="certificate">
          <el-upload
            class="certificate-upload"
            action="#"
            :auto-upload="false"
            :file-list="trainingForm.certificateList"
            :on-change="handleCertificateChange"
            :before-upload="beforeUpload">
            <el-button size="small" type="primary">上传证书</el-button>
            <div slot="tip" class="el-upload__tip">支持jpg、png、pdf格式，不超过5MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="培训说明" prop="description">
          <el-input
            type="textarea"
            v-model="trainingForm.description"
            :rows="3"
            placeholder="请输入培训内容说明">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="trainingDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitTrainingRecord" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ArchiveManagement',
  data() {
    return {
      // 基础数据
      activeTab: 'certificates',
      currentEmployee: null,
      employees: [],
      employeesLoading: false,
      submitting: false,

      // 预览相关
      previewVisible: false,
      previewUrl: '',

      // 证件资料
      certificatesList: [],
      certificateDialog: {
        visible: false,
        type: 'add'
      },
      certificateForm: {
        type: '',
        number: '',
        validDate: '',
        permanent: false,
        fileList: [],
        remark: ''
      },
      certificateRules: {
        type: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
        number: [{ required: true, message: '请输入证件号码', trigger: 'blur' }]
      },

      // 工作履历
      workHistory: [],
      workDialog: {
        visible: false,
        type: 'add'
      },
      workForm: {
        company: '',
        position: '',
        dateRange: [],
        description: ''
      },
      workRules: {
        company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
        dateRange: [{ required: true, message: '请选择工作时间', trigger: 'change' }]
      },

      // 培训记录
      trainingRecords: [],
      trainingDialog: {
        visible: false,
        type: 'add'
      },
      trainingForm: {
        course: '',
        type: '',
        dateRange: [],
        duration: 0,
        result: '',
        certificateList: [],
        description: ''
      },
      trainingRules: {
        course: [{ required: true, message: '请输入培训课程', trigger: 'blur' }],
        type: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择培训时间', trigger: 'change' }],
        duration: [{ required: true, message: '请输入培训时长', trigger: 'change' }],
        result: [{ required: true, message: '请选择培训结果', trigger: 'change' }]
      }
    }
  },
  methods: {
    // 员工相关
    async searchEmployees(query) {
      if (query) {
        this.employeesLoading = true
        try {
          // TODO: 调用接口搜索员工
          await new Promise(resolve => setTimeout(resolve, 500))
          this.employees = [
            { id: 1, name: '张三', department: '技术部' },
            { id: 2, name: '李四', department: '人事部' }
          ]
        } finally {
          this.employeesLoading = false
        }
      }
    },
    handleEmployeeChange(employeeId) {
      this.fetchEmployeeArchives(employeeId)
    },
    async fetchEmployeeArchives(employeeId) {
      // TODO: 获取员工档案信息
    },

    // 证件相关
    getCertificateTagType(type) {
      const typeMap = {
        id: '',
        passport: 'success',
        education: 'warning',
        professional: 'primary',
        other: 'info'
      }
      return typeMap[type] || 'info'
    },
    getCertificateTypeName(type) {
      const typeMap = {
        id: '身份证',
        passport: '护照',
        education: '学历证书',
        professional: '职称证书',
        other: '其他证件'
      }
      return typeMap[type] || type
    },
    uploadCertificate() {
      this.certificateDialog.type = 'add'
      this.certificateDialog.visible = true
      this.$nextTick(() => {
        this.$refs.certificateForm?.resetFields()
      })
    },
    async submitCertificate() {
      try {
        await this.$refs.certificateForm.validate()
        this.submitting = true
        // TODO: 保存证件信息
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('保存成功')
        this.certificateDialog.visible = false
        this.fetchEmployeeArchives(this.currentEmployee)
      } catch (error) {
        console.error(error)
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    // 工作履历相关
    getTimeRange(start, end) {
      return `${start} 至 ${end || '现在'}`
    },
    getTimelineItemType(experience) {
      return experience.isCurrent ? 'primary' : ''
    },
    addWorkExperience() {
      this.workDialog.type = 'add'
      this.workDialog.visible = true
      this.$nextTick(() => {
        this.$refs.workForm?.resetFields()
      })
    },
    editWorkExperience(experience) {
      this.workDialog.type = 'edit'
      this.workForm = { ...experience }
      this.workDialog.visible = true
    },
    async submitWorkExperience() {
      try {
        await this.$refs.workForm.validate()
        this.submitting = true
        // TODO: 保存工作经历
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('保存成功')
        this.workDialog.visible = false
        this.fetchEmployeeArchives(this.currentEmployee)
      } catch (error) {
        console.error(error)
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    // 培训记录相关
    getTrainingResultType(result) {
      const typeMap = {
        excellent: 'success',
        good: 'primary',
        pass: 'warning',
        fail: 'danger'
      }
      return typeMap[result] || 'info'
    },
    addTrainingRecord() {
      this.trainingDialog.type = 'add'
      this.trainingDialog.visible = true
      this.$nextTick(() => {
        this.$refs.trainingForm?.resetFields()
      })
    },
    editTrainingRecord(record) {
      this.trainingDialog.type = 'edit'
      this.trainingForm = { ...record }
      this.trainingDialog.visible = true
    },
    async submitTrainingRecord() {
      try {
        await this.$refs.trainingForm.validate()
        this.submitting = true
        // TODO: 保存培训记录
        await new Promise(resolve => setTimeout(resolve, 1000))
        this.$message.success('保存成功')
        this.trainingDialog.visible = false
        this.fetchEmployeeArchives(this.currentEmployee)
      } catch (error) {
        console.error(error)
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    // 文件处理相关
    beforeUpload(file) {
      const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isValidType) {
        this.$message.error('只能上传jpg、png、pdf格式文件!')
      }
      if (!isLt5M) {
        this.$message.error('文件大小不能超过 5MB!')
      }
      return isValidType && isLt5M
    },
    handleFileChange(file) {
      // 处理文件变更
    },
    previewFile(file) {
      this.previewUrl = URL.createObjectURL(file.raw)
      this.previewVisible = true
    },
    async downloadFile(file) {
      try {
        const response = await this.$http.get(`/api/archives/files/${file.id}`, {
          responseType: 'blob'
        })
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', file.name)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        this.$message.error('文件下载失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.archive-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);

  .header {
    margin-bottom: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    
    .header-content {
      position: relative;
      text-align: center;

      .back-btn {
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        text-decoration: none;
        color: #606266;
        display: flex;
        align-items: center;

        &:hover {
          color: #409EFF;
        }

        i {
          margin-right: 5px;
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
    }
  }

  .content {
    .employee-select {
      margin-bottom: 20px;
      text-align: center;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    .experience-card {
      .experience-header {
        margin-bottom: 10px;

        h4 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }

        .experience-position {
          margin-top: 5px;
          color: #409EFF;
          font-size: 14px;
        }
      }

      .experience-content {
        color: #606266;
        font-size: 14px;
        line-height: 1.6;
      }

      .experience-footer {
        margin-top: 15px;
        text-align: right;
      }
    }
  }

  .preview-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
    }

    .preview-container {
      height: 70vh;
      
      iframe {
        width: 100%;
        height: 100%;
      }
    }
  }

  .danger-button {
    color: #F56C6C;
    
    &:hover {
      color: #f78989;
    }
  }

  .unit {
    margin-left: 10px;
    color: #909399;
  }

  :deep(.el-upload-list__item) {
    transition: all 0.3s;
    
    &:hover {
      background-color: #f5f7fa;
    }
  }

  :deep(.el-timeline-item__node) {
    &.el-timeline-item__node--normal {
      left: -2px;
      width: 12px;
      height: 12px;
    }
  }
}
</style> 